import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class GradePanel extends JPanel {
    private JTable gradeTable;
    private DefaultTableModel tableModel;
    private GradeDAO gradeDAO;
    private StudentDAO studentDAO;
    private CourseDAO courseDAO;

    public GradePanel() {
        gradeDAO = new GradeDAO();
        studentDAO = new StudentDAO();
        courseDAO = new CourseDAO();
        setLayout(new BorderLayout(10, 10));

        // 表格
        String[] columnNames = {"学号", "学生姓名", "课程编号", "课程名称", "成绩"};
        tableModel = new DefaultTableModel(columnNames, 0);
        gradeTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(gradeTable);
        add(scrollPane, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));

        JButton addButton = new JButton("添加");
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showAddDialog();
            }
        });
        buttonPanel.add(addButton);

        JButton editButton = new JButton("修改");
        editButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = gradeTable.getSelectedRow();
                if (selectedRow >= 0) {
                    String studentId = (String) tableModel.getValueAt(selectedRow, 0);
                    String courseId = (String) tableModel.getValueAt(selectedRow, 2);
                    showEditDialog(studentId, courseId);
                } else {
                    JOptionPane.showMessageDialog(GradePanel.this,
                            "请先选择要修改的成绩记录", "提示", JOptionPane.WARNING_MESSAGE);
                }
            }
        });
        buttonPanel.add(editButton);

        JButton deleteButton = new JButton("删除");
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = gradeTable.getSelectedRow();
                if (selectedRow >= 0) {
                    String studentId = (String) tableModel.getValueAt(selectedRow, 0);
                    String courseId = (String) tableModel.getValueAt(selectedRow, 2);
                    int option = JOptionPane.showConfirmDialog(GradePanel.this,
                            "确定要删除这条成绩记录吗?", "确认删除",
                            JOptionPane.YES_NO_OPTION);
                    if (option == JOptionPane.YES_OPTION) {
                        if (gradeDAO.deleteGrade(studentId, courseId)) {
                            refreshTable();
                            JOptionPane.showMessageDialog(GradePanel.this,
                                    "删除成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                        } else {
                            JOptionPane.showMessageDialog(GradePanel.this,
                                    "删除失败", "错误", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                } else {
                    JOptionPane.showMessageDialog(GradePanel.this,
                            "请先选择要删除的成绩记录", "提示", JOptionPane.WARNING_MESSAGE);
                }
            }
        });
        buttonPanel.add(deleteButton);

        JButton refreshButton = new JButton("刷新");
        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                refreshTable();
            }
        });
        buttonPanel.add(refreshButton);

        add(buttonPanel, BorderLayout.SOUTH);

        // 查询面板
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        JTextField studentField = new JTextField(10);
        JTextField courseField = new JTextField(10);
        JButton searchButton = new JButton("查询");
        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String studentKeyword = studentField.getText();
                String courseKeyword = courseField.getText();

                if (studentKeyword.isEmpty() && courseKeyword.isEmpty()) {
                    refreshTable();
                } else {
                    searchGrades(studentKeyword, courseKeyword);
                }
            }
        });
        searchPanel.add(new JLabel("学号:"));
        searchPanel.add(studentField);
        searchPanel.add(new JLabel("课程编号:"));
        searchPanel.add(courseField);
        searchPanel.add(searchButton);
        add(searchPanel, BorderLayout.NORTH);

        // 初始化表格数据
        refreshTable();
    }

    private void refreshTable() {
        tableModel.setRowCount(0);
        List<Grade> grades = gradeDAO.getAllGrades();
        for (Grade grade : grades) {
            Student student = studentDAO.getStudentById(grade.getStudentId());
            Course course = courseDAO.getCourseById(grade.getCourseId());

            if (student != null && course != null) {
                Object[] rowData = {
                        grade.getStudentId(),
                        student.getName(),
                        grade.getCourseId(),
                        course.getCourseName(),
                        grade.getScore()
                };
                tableModel.addRow(rowData);
            }
        }
    }

    private void searchGrades(String studentKeyword, String courseKeyword) {
        tableModel.setRowCount(0);
        List<Grade> grades = gradeDAO.getAllGrades();
        for (Grade grade : grades) {
            Student student = studentDAO.getStudentById(grade.getStudentId());
            Course course = courseDAO.getCourseById(grade.getCourseId());

            if (student != null && course != null) {
                boolean studentMatch = studentKeyword.isEmpty() ||
                        grade.getStudentId().contains(studentKeyword) ||
                        student.getName().contains(studentKeyword);
                boolean courseMatch = courseKeyword.isEmpty() ||
                        grade.getCourseId().contains(courseKeyword) ||
                        course.getCourseName().contains(courseKeyword);

                if (studentMatch && courseMatch) {
                    Object[] rowData = {
                            grade.getStudentId(),
                            student.getName(),
                            grade.getCourseId(),
                            course.getCourseName(),
                            grade.getScore()
                    };
                    tableModel.addRow(rowData);
                }
            }
        }
    }

    private void showAddDialog() {
        JDialog dialog = new JDialog();
        dialog.setTitle("添加成绩");
        dialog.setSize(400, 200);
        dialog.setModal(true);
        dialog.setLocationRelativeTo(this);

        JPanel panel = new JPanel(new GridLayout(4, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 学生选择
        JComboBox<String> studentCombo = new JComboBox<>();
        List<Student> students = studentDAO.getAllStudents();
        for (Student student : students) {
            studentCombo.addItem(student.getStudentId() + " - " + student.getName());
        }

        // 课程选择
        JComboBox<String> courseCombo = new JComboBox<>();
        List<Course> courses = courseDAO.getAllCourses();
        for (Course course : courses) {
            courseCombo.addItem(course.getCourseId() + " - " + course.getCourseName());
        }

        JTextField scoreField = new JTextField();

        panel.add(new JLabel("学生:"));
        panel.add(studentCombo);
        panel.add(new JLabel("课程:"));
        panel.add(courseCombo);
        panel.add(new JLabel("成绩:"));
        panel.add(scoreField);

        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    String studentInfo = (String) studentCombo.getSelectedItem();
                    String courseInfo = (String) courseCombo.getSelectedItem();
                    String studentId = studentInfo.split(" - ")[0];
                    String courseId = courseInfo.split(" - ")[0];
                    double score = Double.parseDouble(scoreField.getText());

                    Grade grade = new Grade(studentId, courseId, score);
                    if (gradeDAO.addGrade(grade)) {
                        refreshTable();
                        dialog.dispose();
                        JOptionPane.showMessageDialog(GradePanel.this,
                                "添加成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                    } else {
                        JOptionPane.showMessageDialog(GradePanel.this,
                                "添加失败，该学生这门课的成绩可能已存在", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(GradePanel.this,
                            "成绩必须是数字", "输入错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        panel.add(saveButton);

        JButton cancelButton = new JButton("取消");
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        });
        panel.add(cancelButton);

        dialog.add(panel);
        dialog.setVisible(true);
    }

    private void showEditDialog(String studentId, String courseId) {
        Grade grade = gradeDAO.getGrade(studentId, courseId);
        if (grade == null) return;

        Student student = studentDAO.getStudentById(studentId);
        Course course = courseDAO.getCourseById(courseId);
        if (student == null || course == null) return;

        JDialog dialog = new JDialog();
        dialog.setTitle("修改成绩");
        dialog.setSize(400, 200);
        dialog.setModal(true);
        dialog.setLocationRelativeTo(this);

        JPanel panel = new JPanel(new GridLayout(4, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        JTextField studentField = new JTextField(student.getStudentId() + " - " + student.getName());
        studentField.setEditable(false);
        JTextField courseField = new JTextField(course.getCourseId() + " - " + course.getCourseName());
        courseField.setEditable(false);
        JTextField scoreField = new JTextField(String.valueOf(grade.getScore()));

        panel.add(new JLabel("学生:"));
        panel.add(studentField);
        panel.add(new JLabel("课程:"));
        panel.add(courseField);
        panel.add(new JLabel("成绩:"));
        panel.add(scoreField);

        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    double newScore = Double.parseDouble(scoreField.getText());
                    grade.setScore(newScore);

                    if (gradeDAO.updateGrade(grade)) {
                        refreshTable();
                        dialog.dispose();
                        JOptionPane.showMessageDialog(GradePanel.this,
                                "修改成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                    } else {
                        JOptionPane.showMessageDialog(GradePanel.this,
                                "修改失败", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(GradePanel.this,
                            "成绩必须是数字", "输入错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        panel.add(saveButton);

        JButton cancelButton = new JButton("取消");
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        });
        panel.add(cancelButton);

        dialog.add(panel);
        dialog.setVisible(true);
    }
}
